import socket from '@ohos.net.socket';
import { BusinessError, Callback } from '@ohos.base';
import buffer from '@ohos.buffer';

import { Convert } from '../util/Convert'

const TAG = "CarUtil";

interface SocketInfo {
  message: ArrayBuffer;
  remoteInfo: socket.SocketRemoteInfo;
}

class CarUtil {
  private udpSocket: socket.UDPSocket = socket.constructUDPSocketInstance();
  private onMessageCallback: ((data: string) => void) | null = null;
  private targetIp: string = "";
  private targetPort: number = 0;
  private isInit = false;

  public initUdp(listenAddress: string, listenPort: number, targetIp:string, targetPort: number,
                     onMessageCallback: (data: string) => void) {
    if (this.isInit) {
      return;
    }
    this.targetIp = targetIp;
    this.targetPort = targetPort;

    let netAddress: socket.NetAddress = {
      address: this.targetIp,
      port: this.targetPort,
      family: 1
    }
    this.onMessageCallback = onMessageCallback;

    this.udpSocket.bind(netAddress).then(() => {
      console.info(TAG, "bind success: " + JSON.stringify(netAddress));
      this.sendMessage('dataSend')
      this.udpSocket.on('message',(data) => {
        console.info(TAG, "bindsuccess" );

        this.onMessage(data);
      });
      this.udpSocket.on('error',(err)=>{
        console.info(TAG, "bindudpSocketon error: " + JSON.stringify(err))
      })
      this.isInit = true;

    })
      .catch((err: BusinessError) => {
        console.error(TAG, "bind error: " + JSON.stringify(err));
    })



    // this.sendMessage('dataSend')
    // this.udpSocket.on('message',(data) => {
    //   console.info(TAG, "bindsuccess" );
    //
    //   this.onMessage(data);
    // });
    // this.udpSocket.on('error',(err)=>{
    //   console.info(TAG, "bindudpSocketon error: " + JSON.stringify(err))
    // })

  }


  private sendMessage(datasend:string ) {
    let address: socket.NetAddress = {
      address: this.targetIp,
      port: this.targetPort,
      family: 1
    }
    let options: socket.UDPSendOptions = {
      data:datasend,
      address: address
    }

    console.info(TAG, `sendMessage: ${this.targetIp}:${this.targetPort} ${JSON.stringify(datasend)}`)
    this.udpSocket.send(options).then(() => {
      console.info(TAG, "sendMessage success");



    }).catch((err: BusinessError) => {
      console.error(TAG, "sendMessage error: " + JSON.stringify(err))
    })
  }

  private onMessage(data: SocketInfo) {
    console.error(TAG, "sendMessage onMessage: " + JSON.stringify(data))

    if (this.onMessageCallback) {

      let message = buffer.from(data.message).toString('hex');
      // let message = this.arrayBuffer2Hex(data.message);
      console.error(TAG, "onMessageCallback " + JSON.stringify(message))
      this.onMessageCallback(message);
    }
  }

  // ArrayBuffer转16进制字符串



}

export default new CarUtil as CarUtil;